package com.example.venue_reservation_service.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.Query;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.venue_reservation_service.domain.Question;
import com.example.venue_reservation_service.domain.Reply;
import com.example.venue_reservation_service.domain.User;
import com.example.venue_reservation_service.dto.QuestionDTO;
import com.example.venue_reservation_service.dto.QuestionQueryDTO;
import com.example.venue_reservation_service.dto.ReservationDTO;
import com.example.venue_reservation_service.mapper.AdminMapper;
import com.example.venue_reservation_service.mapper.QuestionMapper;
import com.example.venue_reservation_service.mapper.ReplyMapper;
import com.example.venue_reservation_service.mapper.UserMapper;
import com.example.venue_reservation_service.service.QuestionService;
import com.example.venue_reservation_service.vo.QueryVO;
import com.example.venue_reservation_service.vo.Result;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Objects;
import java.util.Optional;

/**
* @author 31586
* @description 针对表【venue_question(用户答疑记录表)】的数据库操作Service实现
* @createDate 2025-06-21 14:15:36
*/
@Service
@Slf4j
public class QuestionServiceImpl extends ServiceImpl<QuestionMapper, Question>
    implements QuestionService{

    @Resource
    private UserMapper userMapper;

    @Resource
    private AdminMapper adminMapper;

    @Resource
    private ReplyMapper replyMapper;

    @Override
    public Result create(QuestionDTO dto) {

        String word = dto.getDescription().trim();
        Question question = lambdaQuery()
                .eq(Question::getDescription, word)
                .eq(Question::getUserId, dto.getUserId())
                .one();

        if(Optional.ofNullable(question).isPresent()) {
            question.setCreatedTime(LocalDateTime.now());
        }else {
            question = BeanUtil.copyProperties(dto, Question.class);
            question.setStatus(0);
            question.setCreatedTime(LocalDateTime.now());
        }
        question.setToUser(1);
        question.setToAdmin(1);
        saveOrUpdate(question);
        return Result.ok(question).message("保存问题成功");
    }

    @Override
    public Result userPage(QuestionQueryDTO dto) {
        Page<Question> page = new Page<>(dto.getCurrent(), dto.getSize());
        User user = userMapper.selectById(dto.getUserId());
        if (Optional.ofNullable(user).isEmpty()) {
            return Result.fail().message("用户信息不存在");
        }
        LambdaQueryWrapper<Question> wrapper = Wrappers.lambdaQuery();
        Integer type = user.getType();
        if(type == 3){
            // 管理员查看所管理场馆中的订单
            String venue = adminMapper.selectVenueByUserId(user.getId());
            wrapper.eq(Question::getType, venue)
                    .eq(Question::getToAdmin, 1);
        }else{
            wrapper.eq(Question::getUserId, user.getId())
                    .eq(Question::getToUser, 1);
        }
        if(dto.getStatus() != 2){
            wrapper.eq(Question::getStatus, dto.getStatus());
        }
        wrapper.orderByDesc(Question::getCreatedTime);
        page = page(page, wrapper);
        QueryVO<Question> vo = new QueryVO<>();
        vo.setList(page.getRecords());
        vo.setTotal(page.getTotal());
        return Result.ok(vo).message("查询成功");
    }

    @Override
    public Result remove(Integer userId, Integer id) {
        Question question = getById(id);
        if (Optional.ofNullable(question).isEmpty()) {
            return Result.fail().message("未查询到问题信息");
        }
        if (!Objects.equals(question.getUserId(), userId)) {
            return Result.fail().message("非本人提问，不可删除");
        }
        User user = userMapper.selectById(userId);
        if(user.getType() == 3){
            question.setToAdmin(0);
        }else{
            question.setToUser(0);
        }
        if (question.getToUser() == 0 && question.getToAdmin() == 0 && question.getStatus() == 1) {
            replyMapper.delete(Wrappers.<Reply>lambdaQuery().eq(Reply::getQuestionId, id));
            removeById(id);
        }else{
            updateById(question);
        }
        return Result.ok(question).message("移除成功");
    }

}




